# 服务端代码
import socket


# 获取客户端数据并且读取文件
def get_client_data(client_socket):
    file_name = client_socket.recv(1024).decode("utf-8")
    data = None
    try:
        f = open(file_name, "rb")
        data = f.read()
        f.close()
    except Exception as error:
        client_socket.send("error")
    return data


# 将数据发送到客户端
def send_2_data(data, client_socket):
    # 如果有数据将发送到客户端
    if data:
        client_socket.send(data)
        client_socket.close()


def run():
    # 创建服务器套接字
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定服务器本地ip和端口
    address = ("192.168.153.1", 8080)
    server.bind(address)
    server.listen(10)

    # 等待客户端链接
    client_socket, addr_socket = server.accept()
    print(addr_socket)
    # 读取文件信息
    data = get_client_data(client_socket)
    # 发送数据到客户端
    send_2_data(data, client_socket)
    # 关闭服务器
    server.close()


if __name__ == "__main__":
    run()
